#region Using directives

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Microsoft.Crm.DataBindining;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using Core = Microsoft.Office.Core;
using CollapsableControl;

#endregion

namespace CRMScenarios
{
    public partial class MultiSelectSearchPane : CRMScenarios.BaseUserControl
    {
        private System.Windows.Forms.DataGridView[] DataGridsPerEntity;
        private System.Windows.Forms.DataGridView dgvSummary;//TO DO Remove this
        BusinessEntityCollection[] currentRelatedBec = null;
        string[] savedQueryDetails = null;
        Core.CommandBarButton[] btnArray = null;
        string[][] MainComboMapping = null;
        PageInfo pageInfo = null;
        bool viewComboSearch = false;
        Point loc = new Point();
        int count = 0;
        
        ActionsPane _parentPane = null;
        object _ActiveApp = null;
        //Smart Search Control
        private static Core.CommandBar[] _contexSenstiveMenus = null;
        private static Core.CommandBarPopup[] _contexMenuPopUpForEachCommandBar = null;
        private static Core.CommandBarButton[] _btnsPerEntity = null;
        private static ArrayList aListContextMenus = new ArrayList();


        ArrayList CollapsablePanelArray = new ArrayList();
        int _remain_space = 0;
        public MultiSelectSearchPane(Object objParentPane)
        {
            InitializeComponent();
            _parentPane = (ActionsPane)objParentPane;
            this.SizeChanged += new EventHandler(MultiSelectSearchPane_SizeChanged);
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }
        public override void initializeControls(object application, object activeOne)
        {
            Application = application;
            ActiveOne = activeOne;
            InfoStatus = new InfoOptions();
            InfoStatus = InfoOptions.Free;
            thisRecord = null;
            _ActiveApp = activeOne;
            MainComboMapping = CrmConnector.getEntityListFromCRM(PrivilegeType.Read);
            string[] entityList = MainComboMapping[0];
            if ((entityList == null) || (entityList.Length == 0))
            {
                return;
            }
            populateListBox(ref lstBoxEntities, entityList);

            if (application is Word.Application)
                OfficeApi.GetControlsFromDocument(activeOne);
            else if (application is Excel.Application)
                OfficeApi.GetControlsFromDocument(application);

            AddEventHandlerToDocumentControls();
            OfficeApi.SetCustomProperty(activeOne, "3", "CRMVSTO");
            if (OfficeApi.GetCustomProperty(activeOne, "CRMVSTO") != null)
            {
                if(OfficeApi.GetCustomProperty(activeOne, "CRMVSTO").ToString().Equals("3"))
                    PrePopulateActionPane(null, null);
            }
            lstBoxEntities.Sorted = true;
            picHelp.Location = new System.Drawing.Point(20, btnOk.Location.Y);
            picHelp.Visible = true;
            picHelp.Enabled = true;
            picHelp.Parent = main_panel;
            lnkLblTips.Location = new System.Drawing.Point(picHelp.Location.X + 25, btnOk.Location.Y);
            lnkLblTips.Visible = true;
            lnkLblTips.Enabled = true;
            lnkLblTips.Parent = main_panel;
            lnkLblTips.MouseHover += new EventHandler(UnderLineTheLabel);
            lnkLblTips.MouseLeave += new EventHandler(UndoUnderLineTheLabel);
            btnOk.Parent = main_panel;
            btnOk.Visible = true;
        }

        private void PrePopulateActionPane(object sender, EventArgs e)
        {
            if (OfficeApi.GetCustomProperty(_ActiveApp, "Selected Entity") != null && OfficeApi.GetCustomProperty(_ActiveApp, "Selected Values") != null)
            {
                String strEntityName = OfficeApi.GetCustomProperty(_ActiveApp, "Selected Entity").ToString();
                String strSelectedValue = OfficeApi.GetCustomProperty(_ActiveApp, "Selected Values").ToString();
                UnselectAllSelectedItems();
                lstBoxEntities.SelectedItem = strEntityName;
                txtLookFor.Text = strSelectedValue.Trim();
                btnGo_Click(sender, e);
                this.Visible = true;
            }
            else
            {
                _parentPane.Controls.Clear();
                _parentPane.Controls.Add(_parentPane.InsertPanel);
            }
        }

        private void UnselectAllSelectedItems()
        {
            for (int iCount = 0; iCount < lstBoxEntities.Items.Count; iCount++)
            {
                lstBoxEntities.SetSelected(iCount, false);
            }
        }
        private void AddEventHandlerToDocumentControls()
        {
            try
            {
                btnArray = new Microsoft.Office.Core.CommandBarButton[5];
                _contexSenstiveMenus = OfficeApi.GetContextMenuCommandBars();
                int iContextSenstiveMenus = 0;
                if (_ActiveApp is Excel.Workbook)
                    iContextSenstiveMenus = OfficeApi.ContextMenuNamesForExcel.Length;
                else
                    iContextSenstiveMenus = OfficeApi.ContextMenuNames.Length;

                for (int iCount = 0; iCount < iContextSenstiveMenus; iCount++)
                {
                    Core.CommandBar ContextSenstiveMenu = _contexSenstiveMenus[iCount];
                    Core.CommandBarPopup ControlSearch = (Core.CommandBarPopup)ContextSenstiveMenu.Controls["Search in CRM"];
                   
                    int iControlCount = ControlSearch.Controls.Count;
                    
                    aListContextMenus.Add(btnArray);
                    int icntCount = 0;
                    foreach (Core.CommandBarButton btnPerEntity in ControlSearch.Controls)
                    {
                        btnArray[icntCount] = btnPerEntity;
                        btnArray[icntCount++].Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(ActionsPaneControl1_Click);
                    }
                }
            }
            catch(Exception exp)
            {
            }

        }

        void ActionsPaneControl1_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            PrePopulateActionPane(Ctrl, null);
            _parentPane.Controls.Clear();
            _parentPane.Controls.Add(_parentPane.MultiSelectPanel);
        }


        //Just For testing otherwise at end we have to use Base User Control API.
        protected string MainEntityName(string entityName)
        {
            int iIndex = index(ref MainComboMapping[0], entityName);
            return ((iIndex != -1) ? (MainComboMapping[1][iIndex]) : (string.Empty));
        }

        //This function will get called if the button ok clicked
        private void btnOk_Click(object sender, EventArgs e)
        {
            structEntityInfo structEntity = GetSelectedDataGridView();
            if (structEntity.DataGridViewEntity != null)
            {
                if (((DataGridView)structEntity.DataGridViewEntity).Rows.Count == 0)
                {
                    MessageBox.Show(ResFixer.Resources.LoadString("NoEntityFoundError"), "Record Select Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    return;
                }

                if (structEntity.DataGridViewEntity.CurrentRow == null)
                {
                    MessageBox.Show(ResFixer.Resources.LoadString("NoEntitySelectedError"), "Record Select Error", MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    return;
                }

                string searchIn = string.Empty;

                ArrayList iIndex = new ArrayList(lstBoxEntities.SelectedItems.Count);
                ArrayList searchedtables = new ArrayList(lstBoxEntities.SelectedItems.Count);
                string selectedtable = string.Empty;

                iIndex.Add(index(ref MainComboMapping[0], structEntity.strEntityName));
                searchedtables.Add((((int)iIndex[0] != -1) ? (MainComboMapping[1][(int)iIndex[0]]) : (string.Empty)));

                int counter = 0;
                foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
                {

                    if (objColapsablePanel.IsCollapsed())
                    {
                        counter++;
                    }
                    else
                        break;
                }

                searchIn = searchedtables[0].ToString();


                if (structEntity.DataGridViewEntity != null)
                {
                    if ((currentRelatedBec[counter] != null) && (currentRelatedBec[counter].BusinessEntities.Length >= structEntity.DataGridViewEntity.Rows[0].Index))
                    {
                        _parentPane.InsertPanel.RefreshAccordingToTheOtherPane(structEntity.strEntityName, string.Empty, ref currentRelatedBec[counter].BusinessEntities[0], RefreshOption.FromTB);
                        _parentPane.InsertPanel.Refresh();
                        _parentPane.Controls.Clear();
                        _parentPane.Controls.Add(_parentPane.InsertPanel);
                        _parentPane.InsertPanel.getDetailsOfTheEntityAndDisplay(currentRelatedBec[counter].BusinessEntities[structEntity.DataGridViewEntity.CurrentRow.Index], searchIn);

                    }
                }
            }
        }

    /// <summary>
    /// Core function for creating collapsible panes and populating them with data
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
        void btnGo_Click(object sender, EventArgs e)
        {
            count = 0;
            cmbView.Text = string.Empty;
            cmbView.Items.Clear();
            viewComboSearch = false;
            
            if (lstBoxEntities.SelectedItems.Count > 10)
            {
                MessageBox.Show(ResFixer.Resources.LoadString("MaximumEntityExceedError") + lstBoxEntities.SelectedItems.Count.ToString(), "Search Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                return;
            }
            currentRelatedBec = new BusinessEntityCollection[lstBoxEntities.SelectedItems.Count];

            btnGo.Enabled = false;
            
            search_panel.Visible = true;
            search_panel.Parent = main_panel;

            //Remove the existing collapsible panels (if exist) for new search
            while (0 < search_panel.Controls.Count)
            {
                search_panel.Controls.RemoveAt(0);
            }

            CollapsablePanelArray.Clear();
            //for (int count = CollapsablePanelArray.Count; count > 0; count--)
            //{
            //    CollapsablePanelArray.RemoveAt(count - 1);
            //}

            BusinessEntityCollection becRetrievedEntities = null;
            string searchPattern = txtLookFor.Text.Trim();
            string[] searchInEntities = new string[lstBoxEntities.SelectedItems.Count];

            //string searchIn = MainEntityName(true);
            string searchIn = string.Empty;

            int selectedEntityCount = lstBoxEntities.SelectedItems.Count;
           
            DataGridsPerEntity = new DataGridView[selectedEntityCount];
            for (int iGridsCount = 0; iGridsCount < DataGridsPerEntity.Length; iGridsCount++)
            {
                DataGridsPerEntity[iGridsCount] = new DataGridView();
                DataGridsPerEntity[iGridsCount].Visible = true;
            }

            //Relocation math
            
            int ContentPaneHeight = (search_panel.Height - 16) - selectedEntityCount * 23;
            loc = new Point(search_panel.Location.X + 3, search_panel.Location.Y + 3);
            
            System.Drawing.Size size = new System.Drawing.Size(this.Size.Width - 20, ContentPaneHeight + 23);
            int height = 0;
            for (int j = 0; selectedEntityCount > 0; j++, selectedEntityCount--)
            {
                
                if (j != 0)
                {
                    size = new System.Drawing.Size(this.Size.Width - 20, 23);
                    loc = new System.Drawing.Point(search_panel.Location.X + 3, search_panel.Location.Y + height);
                }

                string entityName = lstBoxEntities.SelectedItems[j].ToString();
                CollapsablePanel collapsiblePanel1 = CreateCollapsiblePanel(entityName, loc, size);
                OfficeApi.AddSearchedEntityIntoCache(entityName);
                height += collapsiblePanel1.Height;
                collapsiblePanel1.Parent = search_panel;
                collapsiblePanel1.ContentPane_HEIGHT = ContentPaneHeight;
                CollapsablePanelArray.Add(collapsiblePanel1);
                collapsiblePanel1.button1.Click += new System.EventHandler(this.collapse_click);
            }
            
            //Creating collapsible panels
            for (int i = 0; i < lstBoxEntities.SelectedItems.Count; i++)
            {
                int iIndex = index(ref MainComboMapping[0], (string)this.lstBoxEntities.SelectedItems[i]);
                searchIn = ((iIndex != -1) ? (MainComboMapping[1][iIndex]) : (string.Empty));

                pageInfo = new PageInfo();

                search_panel.Visible = true;
                search_panel.Focus();

                CollapsablePanel collapsiblePanel1 = (CollapsablePanel)CollapsablePanelArray[i];
                ((CollapsablePanel)CollapsablePanelArray[i]).Visible = true;
                collapsiblePanel1.Visible = true;
                collapsiblePanel1.Parent = search_panel;
                Panel gridViewPanel = new System.Windows.Forms.Panel();
                gridViewPanel.Location = new System.Drawing.Point(0, 0);
                gridViewPanel.Size = new System.Drawing.Size(240, ContentPaneHeight);
                gridViewPanel.Name = "panel" + i.ToString(System.Globalization.CultureInfo.CurrentUICulture);
                gridViewPanel.Dock = DockStyle.Fill;
                gridViewPanel.Visible = true;

                collapsiblePanel1.ContentPane = gridViewPanel;
                collapsiblePanel1.ContentPane_HEIGHT = ContentPaneHeight;
                
                DataGridsPerEntity[i].Location = new System.Drawing.Point(0, 0);
                DataGridsPerEntity[i].Dock = System.Windows.Forms.DockStyle.Fill;
                DataGridsPerEntity[i].Parent = gridViewPanel;
                DataGridsPerEntity[i].CellDoubleClick += new DataGridViewCellEventHandler(btnOk_Click);
                DataGridsPerEntity[i].MultiSelect = false;
                //Creates data grid and populates with search results.
                
                if (false == PageChange(pageInfo.FirstPage(), searchIn, DataGridsPerEntity[i]))
                    return;

                count++;

                collapsiblePanel1.Button_Text = (string)this.lstBoxEntities.SelectedItems[i] + " - " + DataGridsPerEntity[i].Rows.Count.ToString();
            }

            if (CollapsablePanelArray.Count > 0)
                ((CollapsablePanel)CollapsablePanelArray[0]).ExpandThisPane();


            btnGo.Enabled = true;

            //Enable select only if some entity is there with search result
            if (CollapsablePanelArray.Count <= 0)
                this.btnOk.Enabled = false;
            else
                this.btnOk.Enabled = true;

            int countOfEntities = -1;

            if ((searchPattern == null) || (searchPattern == string.Empty))
            {
                return;
            }

            becRetrievedEntities = CrmConnector.DoRealSearchBringMinimal(searchIn, searchPattern, null);

            switch (countOfEntities)
            {
                case -1:
                    break;

                case 0: 
                    break;

                case 1:                    

                default:
                    break;
            }

            btnOk.Visible = true;
            btnOk.Parent = main_panel;
        }

    /// <summary>
    /// On double click of a record on the search results(grid), moves to the insert pane
    /// and displays the info of the selected record.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
        void gridViewRecords_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            structEntityInfo structEntity = GetSelectedDataGridView();
            if (structEntity.DataGridViewEntity != null)
            {
                if (((DataGridViewCellEventArgs)e).RowIndex < 0)
                {
                    return;
                }
                if ((currentRelatedBec[count] != null) && (currentRelatedBec[count].BusinessEntities.Length >= structEntity.DataGridViewEntity.Rows[0].Index))
                {
                    //_parentPane.InsertPanel.RefreshAccordingToTheOtherPane(structEntity.strEntityName, string.Empty, ref currentRelatedBec[count].BusinessEntities[structEntity.DataGridViewEntity.Rows[0].Index], RefreshOption.FromTB);
                    //_parentPane.InsertPanel.Refresh();
                    //_parentPane.Controls.Clear(); 
                    //_parentPane.Controls.Add(_parentPane.InsertPanel);
                    //_parentPane.InsertPanel.getDetailsOfTheEntityAndDisplay(currentRelatedBec[count].BusinessEntities[e.RowIndex], currentRelatedBec[count].EntityName);
                    _parentPane.changeScenario(2, structEntity.strEntityName, this.txtLookFor.Text,ref  currentRelatedBec[count].BusinessEntities[e.RowIndex], RefreshOption.FromSearch);
                }
            }

        }
    
        private structEntityInfo GetSelectedDataGridView()
        {
            structEntityInfo structTemp = new structEntityInfo();
            structTemp.strEntityName = string.Empty;
            structTemp.DataGridViewEntity = null;

            foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
            {
                if ((objColapsablePanel.ContentPane != null) && (!objColapsablePanel.IsCollapsed()))
                {
                    foreach (Control cntrl in objColapsablePanel.ContentPane.Controls)
                    {
                        if (cntrl is DataGridView)
                        {
                            structTemp = new structEntityInfo();
                            structTemp.DataGridViewEntity = (DataGridView)cntrl;
                            structTemp.strEntityName = objColapsablePanel.Title;
                        }
                        break;
                    }
                    break;
                }

            }
            return structTemp;
        }
        struct structEntityInfo
        {
            public String strEntityName;
            public DataGridView DataGridViewEntity;
        }


    /// <summary>
    /// Gets a new Collapsible panel.    
    /// </summary>
    /// <param name="title"></param>
    /// <param name="location"></param>
    /// <param name="size"></param>
    /// <returns></returns>
        public CollapsablePanel CreateCollapsiblePanel(string title, System.Drawing.Point location, System.Drawing.Size size)
        {
            CollapsablePanel col = new CollapsablePanel();
            col.Location = location;
            col.Size = size;
            col.Parent = this.FindForm();
            col.Title = title;
            col.Button_Text = title;
            return col;

        }

        private bool PageChange(PagingInfo pInfo,String strEntityName,DataGridView DataGridForEntity)
        {
            string entityType = strEntityName;
            string search =  txtLookFor.Text;
            string searchPattern = (((search == null) || (search == string.Empty)) ? ("*") : (search));
            string[] columnNames = null;
            if (!viewComboSearch)
            {
                currentRelatedBec[count] = CrmConnector.SearchQkBringLookUp(entityType, searchPattern, pInfo);
                columnNames = CrmConnector.GetQkColumnsIfNoLookUpAvailable(entityType);
            }
            else
            {
                int viewCount = 0;
                //When called from different view selection then find entity which is not collapsed
                foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
                {
                    if (objColapsablePanel.IsCollapsed())
                        viewCount++;
                }

                string[] selectedSavedQuery = SelectedSavedQuery();
                if (selectedSavedQuery == null)
                {
                    currentRelatedBec[viewCount] = null;
                    return false;
                }
                currentRelatedBec[viewCount] = CrmConnector.GetEntitiesWithThisView("*", selectedSavedQuery[1], pInfo, selectedSavedQuery[0], entityType);
                columnNames = CrmConnector.ColumnsFromLayOutXmlForTheView(entityType, selectedSavedQuery[0]);
                if (columnNames == null)
                {
                    columnNames = CrmConnector.getLookupAttributes(selectedSavedQuery[1], "/fetch/entity/attribute", "name");
                }
                count = viewCount;
            }

            if (currentRelatedBec[count] == null)
            {
                Util.ShowError(global::CRMScenarios.Resources.ErrorInSearching);
                return false;
            }

            if (columnNames == null)
            {
                return true;
            }
            FillRelatedRecordsView(entityType, columnNames,DataGridForEntity);
            return true;
        }

        private void FillRelatedRecordsView(string entityType, string[] columnNames, DataGridView DataGridForEntity)
        {

            DataGridForEntity.Columns.Clear();
            dgvSummary = new DataGridView();
            dgvSummary.Rows.Clear();

            if (currentRelatedBec[count] == null)
            {
                DataGridForEntity.Enabled = false;
                return;
            }

            DataGridForEntity.AutoGenerateColumns = true;
            DataGridForEntity.DataError += new DataGridViewDataErrorEventHandler(listViewRecords_DataError);
            IDictionary nameToTypeMap = CrmConnector.GetNameToTypeMapping(entityType, columnNames);
            DataGridForEntity.DataSource = UniversalEntity.CreateFromDynamicEntityCollection(currentRelatedBec[count], ref nameToTypeMap);
            string[] DataBndColumnNames = CrmConnector.GetDataBoundAttribNames(entityType, columnNames);
            StringCollection columNameCollection = CrmConnector.ArrayToCollection(DataBndColumnNames);
            columNameCollection.Remove(CrmConnector.GetEntityMetaData(entityType).PrimaryKey);
            DataGridForEntity.Visible = true;

            foreach (DataGridViewColumn s in DataGridForEntity.Columns)
            {
                if (s != null)
                {
                    s.Visible = false;
                }
            }

            int TotalColumnWidth = 0;
           
            foreach (string lookUpCol in columNameCollection)
            {
                string dispName = CrmConnector.GetDisplayNameOfAttribute(entityType, lookUpCol);
                string displayName = ((dispName == null) || (dispName == string.Empty)) ? (lookUpCol) : (dispName);
                if (DataGridForEntity.Columns.Contains(lookUpCol))
                {
                    DataGridForEntity.Columns[lookUpCol].HeaderText = displayName;
                }
                    else
                {
                        DataGridForEntity.Columns.Add(lookUpCol, displayName);
                }
                    DataGridForEntity.Columns[lookUpCol].DisplayIndex = columNameCollection.IndexOf(lookUpCol);
                    DataGridForEntity.Columns[lookUpCol].Visible = true;
                    DataGridForEntity.Columns[lookUpCol].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    TotalColumnWidth += DataGridForEntity.Columns[lookUpCol].Width;
            }

            if (TotalColumnWidth < DataGridForEntity.Width)
            {
                foreach (string lookUpCol in columNameCollection)
                {
                    DataGridForEntity.Columns[lookUpCol].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }

            DataGridForEntity.Enabled = true;

            if (currentRelatedBec[count].BusinessEntities.Length == 0)
            {

            }


        }

        private void listViewRecords_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }

        private string[] SelectedSavedQuery()
        {
            string[] selectedSavedQuery = null;
            this.txtLookFor.Text = string.Empty;
            if (savedQueryDetails == null)
            {
                return null;
            }
            for (int i = 0; i < savedQueryDetails.Length; i += 2) // Even - name & Odd - query
            {
                if (this.cmbView.Text == savedQueryDetails[i])
                {
                    selectedSavedQuery = new string[2];
                    selectedSavedQuery[0] = savedQueryDetails[i]; // name, at 0
                    selectedSavedQuery[1] = savedQueryDetails[i + 1]; // then at 1, query
                    break;
                }
            }
            return selectedSavedQuery;
        }

        public void TriggerNewSearch(string entityName, string LookFor)
        {
            lstBoxEntities.SelectedItems.Clear();
            lstBoxEntities.SelectedItem = entityName;
            txtLookFor.Text = LookFor;
            btnGo_Click(null, null);
        }

        public void TriggerNewSearch(ArrayList multiSelectBox, string LookFor)
        {
            //Clear old selection
            lstBoxEntities.SelectedItems.Clear();
            //set new entities passed
            for (int index = 0; index < multiSelectBox.Count; index++)
            {
                lstBoxEntities.SelectedItem = multiSelectBox[index].ToString();
            }

            txtLookFor.Text = LookFor;
            btnGo_Click(null, null);
        }

        public void sizeChange(int pWidth, int pHeight)
        {
            this.Location = new Point(0, 0);
            this.Size = new Size(pWidth, pHeight);
        }

        void MultiSelectSearchPane_SizeChanged(object sender, EventArgs e)
        {
            this.search_panel.Size = new Size(this.Width - 10, this.search_panel.Size.Height);
            this.main_panel.Size = new Size(this.Width - 10, this.main_panel.Size.Height);
            foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
            {
                objColapsablePanel.Size = new Size(this.Width - 20, objColapsablePanel.Size.Height);
            }
            lstBoxEntities.Size = new Size(this.Width - lstBoxEntities.Location.X - 10, lstBoxEntities.Size.Height);
            cmbView.Size = new Size(this.Width - cmbView.Location.X - 10, cmbView.Size.Height);
            txtLookFor.Size = new Size(this.Width - txtLookFor.Location.X - 20 - btnGo.Size.Width, txtLookFor.Size.Height);
            btnGo.Location = new System.Drawing.Point(txtLookFor.Location.X + txtLookFor.Size.Width + 10, btnGo.Location.Y);
            btnOk.Location = new System.Drawing.Point(this.Width - btnOk.Size.Width - 10, btnOk.Location.Y);
            picHelp.Location = new System.Drawing.Point(20, btnOk.Location.Y);
            lnkLblTips.Location = new System.Drawing.Point(picHelp.Location.X + 25, btnOk.Location.Y);
        }
        
        private void populateCombo(string[] strings)
        {
            if ((cmbView == null) || (strings == null))
            {
                return;
            }

            foreach (string s in strings)
            {
                cmbView.Items.Add((object)s);
            }

        }

        private void RefreshSavedQueryCombo()
        {
            this.cmbView.Items.Clear();
            if (savedQueryDetails == null)
            {
                return;
            }
            string[] savedQueryNames = new string[savedQueryDetails.Length / 2];
            for (int i = 0; i < savedQueryNames.Length; i++)
            {
                savedQueryNames[i] = savedQueryDetails[2 * i];
            }
            populateCombo(savedQueryNames); // to be managed to get the list of views!!
            this.cmbView.SelectedItem = string.Empty;
        }

        void setView_click(object sender, EventArgs e)
        {
            this.cmbView.Text = string.Empty;
            viewComboSearch = false;
            string entityNotCollapsed = string.Empty;
            foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
            {

                if (!objColapsablePanel.IsCollapsed())
                {
                    entityNotCollapsed = objColapsablePanel.Title;
                }
            }
            if (entityNotCollapsed != string.Empty)
            {
                savedQueryDetails = CrmConnector.GetViewsForLookupDlg(this.MainEntityName(entityNotCollapsed));
                this.RefreshSavedQueryCombo();
            }
        }

        void newViewSelected_click(object sender, EventArgs e)
        {
            string entityNotCollapsed = string.Empty;
            int index = 0;
            foreach (CollapsablePanel objColapsablePanel in CollapsablePanelArray)
            {

                if (!objColapsablePanel.IsCollapsed())
                {
                    entityNotCollapsed = objColapsablePanel.Title;
                    viewComboSearch = true;
                    PageChange(pageInfo.FirstPage(), MainEntityName(entityNotCollapsed), DataGridsPerEntity[index]);
                    objColapsablePanel.Button_Text = objColapsablePanel.Title + " - " + DataGridsPerEntity[index].Rows.Count.ToString();
                }
                index++;
                
            }
            
        }
        void collapse_click(object sender, EventArgs e)
        {
            cmbView.Items.Clear();
            cmbView.Text = string.Empty;
            viewComboSearch = false;
        }

        private void picHelp_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_insert.htm");
        }

        private void lnkLblTips_Click(object sender, EventArgs e)
        {
            GiveHelpOrTips("how_IBF_insert.htm");
        }
        private void UndoUnderLineTheLabel(object sender, EventArgs e)
        {
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Regular, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Default;
        }

        private void UnderLineTheLabel(object sender, EventArgs e)
        {
            ((Label)sender).Font = new Font(((Label)sender).Font.FontFamily, ((Label)sender).Font.Size, FontStyle.Underline, GraphicsUnit.Pixel);
            this.Cursor = Cursors.Hand;
        }


    }
}
